package com.zyx.shiro.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.StrUtil;
import com.zyx.shiro.entity.User;
import com.zyx.shiro.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户接口
 *
 * @author zyx
 * @since 2023/9/9 01:06
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    /**
     * 随机4位数字与字符生成器，可重复
     */
    private final RandomGenerator generator = new RandomGenerator(4);

    /**
     * 用户注册
     */
    @RequestMapping(value = "register", method = {RequestMethod.POST})
    public String register(User user) {
        try {
            userService.register(user);
            return "redirect:/login.jsp";
        } catch (Exception ex) {
            log.error("execute exception:{}", ex.getMessage(), ex);
            return "redirect:/register.jsp";
        }
    }

    /**
     * 用来处理身份认证
     */
    @RequestMapping(value = "login", method = {RequestMethod.POST})
    public String login(String username, String password, String code, HttpSession session) {
        // 比较验证码
        String sessionCode = (String) session.getAttribute("code");
        try {
            if (StrUtil.equalsIgnoreCase(sessionCode, code)) {
                // 获取主体对象
                Subject subject = SecurityUtils.getSubject();
                subject.login(new UsernamePasswordToken(username, password));
                return "redirect:/index.jsp";
            } else {
                throw new RuntimeException("验证码错误!");
            }
        } catch (UnknownAccountException ex) {
            log.error("execute exception:{}", ex.getMessage(), ex);
            log.error("用户名错误!");
        } catch (IncorrectCredentialsException ex) {
            log.error("execute exception:{}", ex.getMessage(), ex);
            log.error("密码错误!");
        }
        return "redirect:/login.jsp";
    }


    /**
     * 退出登录
     */
    @RequestMapping(value = "logout", method = {RequestMethod.POST})
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        // 退出用户
        subject.logout();
        return "redirect:/login.jsp";
    }

    @RequestMapping("getImage")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 40);
        captcha.setGenerator(generator);
        // 重新生成code
        captcha.createCode();
        // 验证码放入session
        log.info("code = {}", captcha.getCode());
        session.setAttribute("code", captcha.getCode());
        // 验证码存入图片
        response.setContentType("image/png");
        captcha.write(response.getOutputStream());
    }


}
